package com.service.gateway.controller;


import com.service.gateway.config.Monitor;
import com.service.gateway.dynamicRouteService.DynamicRouteServiceImpl;


import com.service.gateway.model.GatewayRouteDefinition;



import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author
 * @version 1.0
 * @date 2020/11/17 16:36
 */
@RestController
@RequestMapping("/route")
public class RouteController {

    @Resource
    private DynamicRouteServiceImpl dynamicRouteService;
    @Resource
    private RouteDefinitionLocator routeDefinitionLocator;

    //增加路由
    @PostMapping("/add")
    public String add(@RequestBody GatewayRouteDefinition gwDefinition) {
        String flag = "fail";
        try {
            RouteDefinition definition = assembleRouteDefinition(gwDefinition);
            flag = this.dynamicRouteService.add(definition);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    //删除路由
    @DeleteMapping("/routes/{id}")
    public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
        try {
            return this.dynamicRouteService.delete(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    //更新路由
    @PostMapping("/update")
    public String update(@RequestBody GatewayRouteDefinition gwDefinition) {
        System.out.println(gwDefinition);
        RouteDefinition definition = assembleRouteDefinition(gwDefinition);
        return this.dynamicRouteService.update(definition);
    }
    //获取网关所有的路由信息
    @RequestMapping("/getRouteDefinitions")
    public Flux<RouteDefinition> getRouteDefinitions(){
        return routeDefinitionLocator.getRouteDefinitions();
    }
    //把传递进来的参数转换成路由对象
    private RouteDefinition assembleRouteDefinition(GatewayRouteDefinition gwDefinition) {
        Monitor monitor = new Monitor();
        RouteDefinition routeDefinition = monitor.assembleRouteDefinition(gwDefinition);
        return routeDefinition;
    }
}
